package org.jeecg.modules.travel.rule;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.handler.IFillRuleHandler;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.YouBianCodeUtil;
import org.jeecg.modules.travel.entity.JhTheme;
import org.jeecg.modules.travel.service.IJhThemeService;

/**
 * 主题编号
 * @Create @author wentao.wang
 * @Create @date 2025-04-22 22:27:26
 */
public class ThemeCodeRule implements IFillRuleHandler {

    @Override
    public Object execute(JSONObject params, JSONObject formData) {
        IJhThemeService jhThemeService = (IJhThemeService) SpringContextUtils.getBean("jhThemeServiceImpl");
        String[] strArray = new String[2];
        String parentId = null;//父级id
        if (formData != null && !formData.isEmpty()) {
            Object obj = formData.get("parentId");
            if (obj != null) {
                parentId = obj.toString();
            }
        }
        //如果是最高级,则查询出同级的org_code, 调用工具类生成编码并返回
        if (StringUtils.isBlank(parentId)) {
            Page<JhTheme> page = new Page<>(1,1);
            IPage<JhTheme> pageList = jhThemeService.getMaxCodeDepart(page,"");
            if (pageList.getRecords() == null || pageList.getRecords().isEmpty()) {
                strArray[0] = YouBianCodeUtil.getNextYouBianCode(null);
                strArray[1] = "0";
            } else {
                JhTheme theme = pageList.getRecords().get(0);
                strArray[0] = YouBianCodeUtil.getNextYouBianCode(theme.getThemeCode());
                strArray[1] = String.valueOf(theme.getThemeLevel());
            }
        } else {
            Page<JhTheme> page = new Page<>(1,1);
            IPage<JhTheme> pageList = jhThemeService.getMaxCodeDepart(page,parentId);
            //父级
            JhTheme jhTheme = jhThemeService.getById(parentId);
            if (pageList.getRecords() == null || pageList.getRecords().isEmpty()) {
                // 直接生成当前的部门编码并返回
                strArray[0] = YouBianCodeUtil.getSubYouBianCode(jhTheme.getThemeCode(), null);
                strArray[1] = String.valueOf(jhTheme.getThemeLevel() + 1);
            } else {
                // 获取同级,利用工具类
                JhTheme theme = pageList.getRecords().get(0);
                // 返回生成的当前部门编码
                strArray[0] = YouBianCodeUtil.getSubYouBianCode(jhTheme.getThemeCode(), theme.getThemeCode());
                strArray[1] = String.valueOf(theme.getThemeLevel());
            }
        }
        return strArray;
    }

}
